import { createRouter, createWebHistory } from 'vue-router'
import PageLayout from '@/layout/PageLayout.vue'
// import UserLayout from '@/layout/UserLayout.vue'
import TableLayout from '@/layout/TableLayout.vue'
import { LOGIN_PAGE_PATH, HOME_PAGE_PATH } from '@/mutation-type'

const menu = []
const modules = import.meta.globEager('./modules/*.js', { eager: true })
Object.keys(modules).forEach((key) => {
  if (key.includes('/_')) {
    return
  }
  const mod = modules[key].default || {}
  const modList = Array.isArray(mod) ? [...mod] : [mod]
  menu.push(...modList)
})
menu.sort((a, b) => a['meta']['orderNo'] - b['meta']['orderNo'])
const routes = [
  {
    path: '/',
    component: TableLayout,
    redirect: HOME_PAGE_PATH,
  },
  {
    path: '/home',
    name: 'home',
    component: PageLayout,
    meta: { title: '首页', orderNo: 0 },
    redirect: '/home/index',
    children: [
      {
        path: 'index',
        name: 'home-index',
        component: () => import('@/views/Home/Index.vue'),
      },
    ],
  },
  ...menu,
  // {
  //   path: '/user',
  //   component: UserLayout,
  //   redirect: LOGIN_PAGE_PATH,
  //   hidden: true,
  //   children: [
  //     {
  //       path: 'login',
  //       name: 'user-login',
  //       meta: { title: '登录' },
  //       component: () => import('@/views/Login/Index.vue'),
  //     },
  //     {
  //       path: 'register',
  //       name: 'user-register',
  //       meta: { title: '注册' },
  //       component: () => import('@/views/Login/Register.vue'),
  //     },
  //     {
  //       path: 'forget',
  //       name: 'user-forget',
  //       meta: { title: '找回密码' },
  //       component: () => import('@/views/Login/Forget.vue'),
  //     },
  //     {
  //       path: 'password',
  //       name: 'user-password',
  //       meta: { title: '修改密码' },
  //       component: () => import('@/views/Login/Password.vue'),
  //     },
  //   ],
  // },
  {
    path: '/404',
    component: () => import('@/views/404/Index.vue'),
  },
  {
    path: '/:catchAll(.*)',
    redirect: '/404',
  },
]

const router = createRouter({
  history: createWebHistory(import.meta.env.VITE_PUBLIC_PATH),
  routes,
  strict: true,
  scrollBehavior(to, from, savedPosition) {
    return new Promise((resolve) => {
      if (savedPosition) {
        return savedPosition
      } else {
        if (from.meta.saveSrollTop) {
          const top = document.documentElement.scrollTop || document.body.scrollTop
          resolve({ left: 0, top })
        }
      }
    })
  },
})

export { menu }
export default router
